import { DoubleLeftOutlined } from '@ant-design/icons';
import { Badge, Checkbox, Col, Collapse, Row, Select } from 'antd';
import { useState, useEffect, useMemo, useRef } from 'react';
import { find } from 'lodash';
import IconFont from '@/components/IconFont';
import { useLocation } from 'react-router-dom';
import { useFilterFieldsConfig } from '../../store';
import FieldWrapper from '../FieldWrapper';
import { OrderStateCheckbox } from './orderStateCheckbox';
import {orderFilterItem, orderStateFilterItem} from '@/pages/OrderModule/orderList/components/Filter/constant.js';
import { getStatisticsOp } from '../../../../services';
import Api from '../../../Actions/service';
import ErrorTypeManageModal from "@/views/components/ErrorTypeManage";

const { Panel } = Collapse;
const CheckboxGroup = Checkbox.Group;

const initOrderStateOptions = [
  { value: 10, label: '待审核' },
  { value: 20, label: '待发货' },
  {
    value: 30,
    label: '异常订单',
    children: [
      // { value: '4', label: '异常原因1' },
      // { value: '5', label: '异常原因2' },
    ],
  },
  { value: 40, label: '已发货' },
  { value: 50, label: '已作废' },
  { value: 52, label: '被拆分' },
  { value: 51, label: '被合单' },
];

const wareHouseStateOptions = [
  { value: 10, label: '待拿货' },
  { value: 20, label: '待包装' },
  { value: 30, label: '待发货' },
  { value: 40, label: '已发货' },
  { value: 50, label: '已作废' },
  { value: 60, label: '已取件' },
];

function flattenNestedOptions(options) {
  const result = [];
  function flatten(options) {
    options.forEach((option) => {
      // result.push({ value: option.value, label: option.label });
      result.push({ ...options });

      if (option.children) {
        flatten(option.children);
      }
    });
  }
  flatten(options);
  return result;
}

/**
 * @desc: 筛选框：订单状态组件
 */
export const OrderState = ({ value, onChange, disabled, searchKey, ...args }) => {

  const isInit = useRef(true);
  
  useEffect(()=>{
    getFieldsFunc();
  }, [])

  useEffect(()=>{
    if(searchKey){
      getNumberFunc()
    }
  }, [searchKey])

  disabled = disabled? disabled : [];

  const location = useLocation();
  
  const isUnPayPage = useMemo(()=>{
    return location.pathname === '/views/order/unpay';
  }, [])

  const getFieldsFunc = async () => {
    const promise = [Api.getErrorReasonAll(), getStatisticsOp({ pageType: 1 })];
    Promise.all(promise).then(res=>{
      const arr = res?.[0]?.data || [], obj = res?.[1]?.data || {}, { errorList = [] } = obj;
      const children = arr.filter(item=>item.display).map(item=>{
        let errorObj = {};
        if(errorList?.length){
          const obj = find(errorList, ['errorId', item.id]);
          errorObj = obj ?? {};
        }
        return ({
          label: item.name,
          value: item.id,
          nums: errorObj?.count || 0,
        })
      })
      orderStateOptions[0].nums = obj.noCheck || 0;
      orderStateOptions[1].nums = obj.noShip || 0;
      orderStateOptions[2].nums = obj.error || 0;
      orderStateOptions[2].children = children;
      setOrderStateOptions([...orderStateOptions]);
      if(errorIdArr?.length){
        const newIds = children.filter(item=>errorIdArr.includes(item.value)).map(item=>item.value);
        if(!newIds?.length && stateArr.includes(30)){
          setStateArr(stateArr.filter(item => item != 30));
        }
        setErrorIdArr(newIds);
      }
      // if(isInit.current){
      //   isInit.current = false;
      //   setErrorIdArr(children.map(item=>item.value));
      // }
    })
  }

  const getNumberFunc = async () => {
    const { data, success} = await getStatisticsOp({ pageType: 1 });
    if(success){
      const { errorList = [] } = data || {};
      orderStateOptions[0].nums = data.noCheck || 0;
      orderStateOptions[1].nums = data.noShip || 0;
      orderStateOptions[2].nums = data.error || 0;
      orderStateOptions[2].children.map(item=>{
        let errorObj = {};
        if(errorList?.length){
          const obj = find(errorList, ['errorId', item.value]);
          errorObj = obj ?? {};
        }
        item.nums = errorObj?.count || 0;
      })
      setOrderStateOptions([...orderStateOptions]);
    }
  }

  const [orderStateOptions, setOrderStateOptions] = useState([...initOrderStateOptions]);
  const [openError, setOpenError] = useState(false);

  const [checkedList, setCheckedList] = useState([]);
  const [stateArr, setStateArr] = useState(value.stateArr || []);
  const [errorIdArr, setErrorIdArr] = useState([]);
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(false);
  const realOrderStateOptions = flattenNestedOptions(orderStateOptions);

  const checkedStatus = useMemo(()=>{
    const params = {
      allChecked: false, 
      allIndeterminate: false, 
      groupChecked:false, 
      groupIndeterminate:false
    }
    if(stateArr?.length){
      if(errorIdArr?.length == orderStateOptions[2].children.length){
        params.groupChecked = true;
      }else if(errorIdArr?.length){
        params.groupIndeterminate = true;
      }
      if(stateArr?.length == orderStateOptions?.length && params.groupChecked){
        params.allChecked = true;
      }else{
        params.allIndeterminate = true;
      }
    }
    return params;
  },[orderStateOptions, stateArr, errorIdArr])

  useEffect(()=>{
    triggerChange({ stateArr, errorIdArr })
  }, [stateArr, errorIdArr])

  const onCheckChange = (list) => {
    // setStateArr(list)
    // setCheckedList(list);
    // setIndeterminate(!!list.length && list.length < realOrderStateOptions.length);
    // setCheckAll(list.length === realOrderStateOptions.length);
    // triggerChange({ stateArr: list });
  };
  const onCheckAllChange = (e) => {
    e.stopPropagation()
    console.log(e.target.checked)
    if(e.target.checked){
      setStateArr(orderStateOptions.map(item=>item.value));
      setErrorIdArr(orderStateOptions[2].children?.map(item=>item.value));
      // const realOrderStateOptions = flattenNestedOptions(orderStateOptions);
    }else{
      setStateArr([]);
      setErrorIdArr([]);
    }

    // const list = e.target.checked ? realOrderStateOptions.map((item) => item.value) : [];
    // triggerChange({ stateArr: list });
    // setIndeterminate(false);
    // setCheckAll(e.target.checked);
  };

  const handleCheck = (value, type) => {
    if(type == 'isBatch'){
      if(value){//Boolean
        setStateArr([...new Set([...stateArr, 30])]);
        setErrorIdArr(orderStateOptions[2].children?.map(item=>item.value));
      }else{
        setStateArr(stateArr.filter(item=>item != 30));
        setErrorIdArr([]);
      }
    }else{
      setErrorIdArr(value);
      if(!value?.length){//Array
        setStateArr(stateArr.filter(item=>item !=30))
      }else if(!stateArr.includes(30)){
        setStateArr([...new Set([...stateArr, 30])]);
      }
    }
  }

  const triggerChange = (changedValue) => {
    console.log(changedValue,'changedValue')
    onChange?.({ ...value, ...changedValue });
  };

  const { checkingMap } = useFilterFieldsConfig();
  if(Object.values(orderStateFilterItem).every(item => checkingMap[item] === false)) {
    return <div style={{marginBottom: -6}}/>
  }

  const ErrorTypeManageProps = {
		handleOk() {
      getFieldsFunc();
			setOpenError(false);
		},
		handleCancel() {
			setOpenError(false);
		}
	}

  return (<>
    {openError && <ErrorTypeManageModal {...ErrorTypeManageProps} />}
    <Collapse
      bordered={false}
      defaultActiveKey={['orderState']}
      expandIcon={({ isActive }) => <DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: '16px', color: '#4E5969' }} />}
      expandIconPosition="end"
    >
      <Panel
        key="orderState"
        className="no-padding"
        header={
          <span onClick={e=>e.stopPropagation()}><Checkbox indeterminate={checkedStatus.allIndeterminate} onChange={onCheckAllChange} checked={checkedStatus.allChecked} disabled={isUnPayPage}>
            订单状态
          </Checkbox></span>
        }
      >
        {checkingMap.stateArr && (
          <Checkbox.Group onChange={value=>setStateArr(value)} value={stateArr} disabled={disabled?.includes('stateArr')}>
            <Row gutter={[0, 10]} style={{ padding: '0px 12px', paddingBottom: '8px' }}>
              {orderStateOptions.map((item, index) => {
                if (item.children) {
                  return <OrderStateCheckbox key={index} checkedStatus={checkedStatus} value={errorIdArr} item={item} children={item.children} isUnPayPage={isUnPayPage} handleCheck={handleCheck} handleOpenErrorConfig={()=>setOpenError(true)}/>;
                } else {
                  return (
                    <Col span={24} key={item.value}>
                      <Checkbox value={item.value}>
                        <div style={{display:"flex",alignItems:'center'}}>{item.label}&nbsp;{[10, 20].includes(item.value) && <Badge count={item.nums} showZero overflowCount={999999}/>}</div>
                      </Checkbox>
                    </Col>
                  );
                }
              })}
            </Row>
          </Checkbox.Group>
        )}
        <div style={{ padding: '0px 12px', paddingBottom: '12px' }}>
          {checkingMap.payStateArr && (
            <FieldWrapper label="支付状态">
              <Select
                value={value.payStateArr}
                disabled={disabled?.includes('payStateArr')}
                mode="multiple"
                onChange={(v) => triggerChange({ payStateArr: v })}
                allowClear
                placeholder="请选择"
                options={[
                  {
                    value: 0,
                    label: '未支付',
                  },
                  {
                    value: 1,
                    label: '已支付',
                  },
                  {
                    value: 3,
                    label: '部分支付',
                  },
                ]}
                clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
              />
            </FieldWrapper>
          )}
          {checkingMap.warehouseOrderStateArr && (
            <FieldWrapper>
              <Select
                mode="multiple"
                value={value.warehouseOrderStateArr}
                allowClear
                placeholder="选择仓库状态"
                options={wareHouseStateOptions}
                onChange={(v) => triggerChange({ warehouseOrderStateArr: v })}
                clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
              />
            </FieldWrapper>
          )}
        </div>
      </Panel>
    </Collapse>
  </>);
};
export default OrderState;
